package com.mgface.framework.springcloud.controller;

import com.mgface.framework.springcloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project ms-ribbon
 * @create 2017-04-10 17:46
 **/
@RestController
public class MovieController {
	//tips:使用RestTemplate时，想要获得一个List时，应该用数组，而不应该直接用List
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private LoadBalancerClient loadBalancerClient;

	@GetMapping("/test")
	public ServiceInstance test() {
		ServiceInstance instance = loadBalancerClient.choose("ms-provider-user");
		return instance;
	}

	/**
	 * 正常来说等到出现异常在配置包含commandProperties属性的@HystrixCommand
	 * @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE"))
	 * THREAD - 它在单独的线程上执行，并发请求受线程池中的线程数限制（default）
	 * SEMAPHORE - 它在调用线程上执行，并发请求受信号量计数限制
	 */
	@GetMapping("/user/{id}")
	@HystrixCommand(fallbackMethod = "findByIdFallback")
	public User findById(@PathVariable Long id) {
		//ms-provider-user这个称为VIP(虚拟IP)->是ms-provider-user项目application.yml属性spring.application.name的设置
		return restTemplate.getForObject("http://ms-provider-user/simple/" + id, User.class);
	}

	public User findByIdFallback(Long id) {
		User user = new User();
		user.setId(id);
		return user;
	}
}
